package com.example.websocket.executor;

import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledThreadPool {
    public static void main(String[] args) {
        ScheduledExecutorService service = Executors.newScheduledThreadPool(5);
        System.out.println("添加任务的时间" + LocalDateTime.now());
        // 延迟执行一次
        service.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("执行子任务1：" + LocalDateTime.now());
            }
        }, 3, TimeUnit.SECONDS);

        // 固定频率执行，以上一次任务开始时间作为下次定时任务的参考时间
        service.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println("执行任务2：" + LocalDateTime.now());
            }
        }, 2, 4, TimeUnit.SECONDS);

       // 固定频率执行，以上一次任务结束时间作为下次定时任务的参考时间
        service.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                System.out.println("执行任务3开始时间：" + LocalDateTime.now());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("执行任务3结束时间：" + LocalDateTime.now());
            }
        }, 2, 4, TimeUnit.SECONDS);
    }
}
